import './Detail.scss'
import {LeftOutline, LikeOutline, MessageOutline, MoreOutline, StarOutline} from "antd-mobile-icons";
import {Badge} from "antd-mobile/2x/es/components/badge/badge.js";
import SkeletonAgain from "@/components/SkeletonAgain.jsx";
import {useEffect, useMemo, useState} from "react";
import {delStore, queryNewsInfo, queryStore, queryStoryExtra} from "@/api/index.js";
import {flushSync} from "react-dom";
import {connect} from "react-redux";
import {action} from "@/store/action/index.js";
import {Toast} from "antd-mobile";


const Detail = function Detail(props) {
    // eslint-disable-next-line react/prop-types
    let {navigate, params} = props;
    let [info, setInfo] = useState(null);
    let [isHasCss, setIsHasCss] = useState(false)

    let style;
    const handleStyle = (result) => {
        let {css} = result;
        const link = css.split(',')[0]
        style = document.createElement('link')
        style.rel = 'stylesheet'
        style.href = link.replace('http://', 'https://')
        document.querySelector('head').appendChild(style)
        flushSync(() => {
            setIsHasCss(true)
        })

    }

    const handleImage = (res) => {
        let imagePlaceholder = document.querySelector('.img-place-holder')
        if (!imagePlaceholder) return;
        let tempImg = new Image()
        tempImg.src = res.image
        tempImg.onload = () => {
            imagePlaceholder.appendChild(tempImg)
        }
        tempImg.onerror = () => {
            let parent = imagePlaceholder.parentNode
            parent.parentNode.removeChild(parent)
        }

    }
    useEffect(() => {
        (async () => {
            try {
                // eslint-disable-next-line react/prop-types
                let {data} = await queryNewsInfo(params.id);
                flushSync(() => {
                    setInfo(data)
                    handleStyle(data)
                })
                handleImage(data)

            } catch (e) {
                console.error(e);
            }
        })()

        return () => {
            if (style) document.head.removeChild(style)
        }
    }, []);
    let {
        location,
        // eslint-disable-next-line react/prop-types
        base: {info: userInfo}, queryUserInfoAsync,        store: {list: storeList},        queryStoreListAsync,        delStoreById
    } = props;
    useEffect(() => {
        (async ()=>{
            if (!userInfo) {
                let {info} = await queryUserInfoAsync()
                // eslint-disable-next-line react-hooks/exhaustive-deps
                userInfo = info
            }
            if (userInfo && !storeList) {
               queryStoreListAsync()
            }
        })()

    }, [])

    const isStore = useMemo(() => {
        if(!storeList) return false;
        // eslint-disable-next-line react/prop-types
        return storeList.some(item => item.id === +params.id)
    }, [storeList,params]);
    const handleStore = async () => {
        if (!userInfo) {
            Toast.show({
                content: '请先登录',
                type: 'warning'
            })
            navigate(`/login?to=${location.pathname}`, {replace: true})
            return;
        }
        if (isStore) {
            let item = storeList.find(item => item.id === +params.id)
            if(!item) return
            let {code} = await delStore(item.id)
            if (code === '200') {
                Toast.show({
                    content: '已取消收藏',
                    type: 'success'
                })
                delStoreById(item.id)
            }

        } else {
           const {code} =  await queryStore(params.id)
            console.log(code)
            if (code === '200') {
                Toast.show({
                    content: '收藏成功',
                    type: 'success'
                })
                queryStoreListAsync()
                return
            }
            Toast.show({
                content: '收藏失败',
                type: 'warning'
            })

        }
    }
    return <div className="detail-box">

        {!info && !isHasCss ? <SkeletonAgain/> :
            <div className="content" dangerouslySetInnerHTML={{__html: info?.body}}></div>
        }
        <div className="tab-bar">
            <div className="back" onClick={() => navigate(-1)}>
                <LeftOutline/>
            </div>
            <div className="icons">
                <Badge content={3}> <MessageOutline/> </Badge>
                <Badge content={3}> <LikeOutline/> </Badge>
                <span className={isStore?'active':''}><StarOutline onClick={handleStore}/></span>
                <span><MoreOutline/></span>
            </div>
        </div>
    </div>
}
export default connect(state => {
    return {
        base: state.base,
        store: state.store
    }
}, {
    ...action.base,
    ...action.store
})(Detail)